# 视频转语音服务主应用

import os
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from .api.router import router as api_router
from .core.config import settings

def create_application() -> FastAPI:
    """
    创建并配置FastAPI应用
    """
    application = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.VERSION,
        docs_url="/docs",
        redoc_url="/redoc",
    )

    # 配置CORS
    cors_origins = settings.cors_origins_list
    if cors_origins and cors_origins[0] == "*":
        # 如果是通配符，直接使用 "*"
        application.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    else:
        # 否则使用配置的具体域名
        application.add_middleware(
            CORSMiddleware,
            allow_origins=cors_origins,
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    # 添加API路由
    application.include_router(api_router, prefix=settings.API_PREFIX)
    
    # 挂载静态文件目录
    os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
    application.mount("/downloads", StaticFiles(directory=settings.OUTPUT_DIR), name="downloads")

    @application.get("/", tags=["健康检查"])
    async def health_check():
        """
        健康检查接口
        """
        return {"status": "healthy", "service": "video-to-speech"}

    return application

# 创建应用实例
app = create_application()

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 8001))
    uvicorn.run("app.main:app", host="0.0.0.0", port=port, reload=True)